package com.demo01.d01;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
    public static void main(String[] args) {
        final Business business = new Business();
        ThreadFactory namedFactoryBuilder = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
        ExecutorService executor = new ThreadPoolExecutor(5, 10, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024), namedFactoryBuilder, new ThreadPoolExecutor.AbortPolicy());
        for (int i = 0; i < 10; i++) {
            executor.execute(
                    new Runnable() {
                        @Override
                        public void run() {
                            business.service();
                        }
                    }

            );
        }
        executor.shutdown();
    }

    private static class Business {
        private int count;
        Lock lock = new ReentrantLock();

        public void service() {
            lock.lock();
            try {
                count++;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " : " + count);
            } catch (RuntimeException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

}
